package com.szalay.desktopsearch.ui;

import com.szalay.desktopsearch.search.SearchListener;
import java.awt.Color;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;

/**
 *  Panel to display the search result.
 * @author szalay
 */
public class SearchResultTable extends JPanel implements SearchListener {
    private static final long serialVersionUID = 8533833186802445083L;

    private final int parentWidth;
    private final Lock lock = new ReentrantLock();
    
    /** Create a new search result table. */
    public SearchResultTable(final int parentWidth) {
        super(false);
        this.parentWidth = parentWidth;
        setLayout(new SpringLayout());
        
        //Set a border
        setBorder(BorderFactory.createRaisedBevelBorder());
    }

    private static final Color ODD_BG = new Color(0xCFCFCF);
    private static final Color EVEN_BG = new Color(0xDFDFDF);
    
    @Override
    public void searchFinished(final QueryResponse response) {
        lock.lock();
        
        try {
            int counter = 0;
            for (final SolrDocument document : response.getResults()) {
                final SearchResultItem item = new SearchResultItem(document, response, parentWidth);
                if ((counter % 2) == 0) {
                    item.setBackground(ODD_BG);
                }
                else {
                    item.setBackground(EVEN_BG);
                }
                add(item);
                counter++;
            }        
            if (counter > 0) {
                UI.makeGrid(this, Scroller.PAGE_SIZE, 1, 5, 5, 10, 10);
            }
            repaint();
        }
        finally {
            lock.unlock();
        }
    }

    @Override
    public void searchStarting(String term) {
        lock.lock();
        removeAll();
        repaint();
        lock.unlock();
    }
}
